<?php
require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));

/**
 * 同步数据到远程数据库
 * Created by PhpStorm.
 * User: cai
 * Date: 16-2-6
 * Time: 下午2:44
 */
class Controller_Triggertable extends Controller
{
    protected $msg = array();
    /**
     * 获取产生触发操作的数据值
     * 相应数据表中的数据值
     */
    public function getdata($warehouse_id,$tablename = '')
    {
        $data = array();

        $warehouse_id = intval($warehouse_id);
        $where        = "warehouseid={$warehouse_id}";
        if(preg_match('/^[\w]+$/',$tablename)){
            $where .= " AND tablename='$tablename'";
        }
        $sql               = "SELECT id,warehouseid,tablename,act,tableid,counter
            FROM triggertable
            WHERE ".$where.'
            ORDER BY id asc
            LIMIT 1000';
        $triggertable_list = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array();

        $update_ids   = array();
        $counter_flag = 0;
        $select_column = '';
        $fbawarehousetable  = Kohana::$config->load('fbawarehousetable');
        $table_config = '';
        if(isset($fbawarehousetable[$tablename])){
            $table_config = $fbawarehousetable[$tablename];
            foreach($table_config['table'] as $key_column => $_column){
                $select_column .= $key_column.' as '.$_column.',';
            }
            $select_column = trim($select_column,',');
        }

        foreach($triggertable_list as $key => $_value){
            $update_ids[] = $_value['id'];

            if ($_value['act'] == "delete") {
                $data[$_value['id']]["data"]["id"] = $_value['tableid'];
            } elseif ($_value['act'] == "add") {
                $sql = "SELECT ".$select_column."
                FROM ".$_value['tablename']."
                WHERE id= ".$_value['tableid']."
                LIMIT 1";

                $temp_data      = DB::query(Database::SELECT,$sql)
                    ->execute('newerp')
                    ->current();

                if(!empty($temp_data) && isset($fbawarehousetable[$tablename]['storename'])) {
                    if(isset($fbawarehousetable[$tablename]['storevalue'][$temp_data[$fbawarehousetable[$tablename]['storename']]])) {
                        $temp_data[$fbawarehousetable[$tablename]['storename']] =
                            $fbawarehousetable[$tablename]['storevalue'][$temp_data[$fbawarehousetable[$tablename]['storename']]];
                    }
                }

                $data[$_value['id']]["data"] = $temp_data;

                if(!(is_array($data[$_value['id']]["data"])&&count($data[$_value['id']]["data"]))){
                    $sql = "DELETE FROM `triggertable` WHERE `id` = ".$_value['id'];
                    DB::query(Database::DELETE,$sql)->execute('newerp');
                    continue;
                }

                //$data[$_value['id']]["data"]["id"]          = $_value['tableid'].substr(sprintf("%03s",$_value['warehouseid']),-3);
                $data[$_value['id']]["data"]["warehouseid"] = $_value['warehouseid'];
                $data[$_value['id']]["data"]["crontrigger"] = 1;
                unset($data[$_value['id']]["data"]["aid"]);
            }elseif($_value['act']=="update"){
                $sql                         = "SELECT ".$select_column."
                FROM ". $_value['tablename']."
                WHERE id = ".$_value['tableid']."
                LIMIT 1";

                $temp_data      = DB::query(Database::SELECT,$sql)
                    ->execute('newerp')
                    ->current();

                if(!empty($temp_data) && isset($fbawarehousetable[$tablename]['storename'])) {
                    if(isset($fbawarehousetable[$tablename]['storevalue'][$temp_data[$fbawarehousetable[$tablename]['storename']]])) {
                        $temp_data[$fbawarehousetable[$tablename]['storename']] =
                            $fbawarehousetable[$tablename]['storevalue'][$temp_data[$fbawarehousetable[$tablename]['storename']]];
                    }
                }

                $data[$_value['id']]["data"] = $temp_data;

                if(!(is_array($data[$_value['id']]["data"])&&count($data[$_value['id']]["data"]))){
                    $sql = "DELETE FROM `triggertable` WHERE `id` = ".$_value['id'];
                    DB::query(Database::DELETE,$sql)->execute('newerp');
                    continue;
                }

                $data[$_value['id']]["data"]["crontrigger"] = 2;
                unset($data[$_value['id']]["data"]["aid"]);
            }

            $data[$_value['id']]["table"]       = $table_config['tablename'][$_value["tablename"]];
            $data[$_value['id']]['warehouseid'] = $_value['warehouseid'];
            $data[$_value['id']]["act"]         = $_value["act"];
            $data[$_value['id']]["tableid"]     = $_value["tableid"];
        }
        if(count($update_ids)){
            $sql = "UPDATE triggertable SET counter=counter+1 WHERE id in(".join($update_ids,',').")";
            DB::query(Database::UPDATE,$sql)
                ->execute('newerp');
        }
        return $data;
    }

    // 实时检测数据表，按仓库查询triggertable中存放的表名
    public function Action_rpcdata()
    {
        $sql    = "SELECT warehouseid,tablename FROM triggertable GROUP BY warehouseid,tablename";
        $tables = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
        // 如果没有记录，则说明无待处理数据
        $row = array_rand($tables,1);

        // 按表处理同步
        $tablename   = $tables[$row]['tablename'];
        $warehouseid = $tables[$row]['warehouseid'];
        // 启动单表同步任务，传递$warehouseid和$tablename两个参数
        $this->rpcdata_single_table($warehouseid,$tablename);
        $this->endTask('Completed ' . date('Y-m-d H:i:s'));

    }

    // 处理单表单批次数据的同步
    public function rpcdata_single_table($warehouse_id,$tablename)
    {
        $config            = Kohana::$config->load('triggerserver');
        $configenvironment = Kohana::$config->load('triggerenvironment');
        $environment_str   = "?environment=".$configenvironment->get('environment');

        $counter  = 0;
        $syn_data = $this->getdata($warehouse_id,$tablename);

        //临时log记录
        //Kohana::$log->add(Log::INFO, 'Rpc data follow');
        //Kohana::$log->add(Log::INFO, var_export($syn_data,TRUE));
        if(!(is_array($syn_data)&&count($syn_data))){
            //无数据的情况
            $this->msg[] =  'rpcdata is null! ['.$warehouse_id.'-->'.$tablename.':'.$counter.'] '.date('Y-m-d H:i:s')."\n";
            //sleep(2);
            return $counter;
        }

        if(is_array($syn_data)&&count($syn_data)){
            $client = new  PHPRPC_Client($config->get('huizongapiserver').$environment_str);

            $triggertable_id_arr = $client->rpcdata($syn_data);
            if(is_array($triggertable_id_arr)&&count($triggertable_id_arr)){
                DB::delete("triggertable")
                    ->where("id","in",$triggertable_id_arr)
                    ->execute("newerp");
            }else{
                print_r($triggertable_id_arr);
                echo "\n";
            }

            $counter += count($triggertable_id_arr);
        }

        echo 'rpcdata success! ['.$warehouse_id.'-->'.$tablename.':'.$counter.'] '.date('Y-m-d H:i:s')."\n";
        return $counter;
    }

    protected function endTask($msg, $code = 0, $data = null) {
        $code = intval($code);
        $msg = addslashes($msg);
        if(!is_null($data)) {
            $data = is_array($data) ? json_encode($data) : $data;
            $dataStr = ",\n\t\"data\": \"" . addslashes($data) . "\"";
        }elseif(!empty($this->msg)) {
            $dataStr = ",\n\t\"data\": \"" . implode("\n\n", $this->msg) . "\"";
        }
        echo "{\n\t\"code\": $code,\n\t\"info\": \"$msg\"{$dataStr}\n}\n";
        exit;
    }
}